﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Modules.Project.Entitys;
using Modules.Project.Repositories;
using Modules.Reports;
using Pipelines.Sockets.Unofficial.Arenas;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Exceptions;

namespace Modules.Project;


/// <summary>
/// 项目解上锁记录服务
/// </summary>
[UseDI(ServiceLifetime.Scoped)]
public class ProjectLockLogService
{
    private readonly ProjectLockLogRepository projectLockLogRepository;
    private readonly ReportProjectMonthService reportProjectMonthService;
    private readonly IApplicationContext applicationContext;
    private readonly ProjectAttachmentService projectAttachmentService;
    private readonly ILogger logger;

    public ProjectLockLogService(ProjectLockLogRepository projectLockLogRepository, ReportProjectMonthService reportProjectMonthService, IApplicationContext applicationContext, ProjectAttachmentService projectAttachmentService, ILogger<ProjectLockLogService> logger)
    {
        this.projectLockLogRepository = projectLockLogRepository;
        this.reportProjectMonthService = reportProjectMonthService;
        this.applicationContext = applicationContext;
        this.projectAttachmentService = projectAttachmentService;
        this.logger = logger;
    }

    /// <summary>
    /// 项目解上锁记录表单详情
    /// </summary>
    /// <param name="id">主键</param>
    /// <returns></returns>
    public ProjectLockLog? Get(int id)
    {
        return projectLockLogRepository.Get(id);
    }

    /// <summary>
    /// 批量删除，根据id
    /// </summary>
    /// <param name="ids">id的集合</param>
    public void Deleted(IEnumerable<int> ids)
    {
        foreach (int id in ids)
        {
            Delete(id);
        }
    }

    /// <summary>
    /// 单个删除
    /// </summary>
    /// <param name="id">主键</param>
    public void Delete(int id)
    {
        projectLockLogRepository.DeleteByEntityId(id);
    }

    /// <summary>
    /// 创建项目解上锁记录
    /// </summary>
    /// <param name="entity">实体对象</param>
    public void Create(ProjectLockLog entity)
    {
        projectLockLogRepository.Insert(entity);
    }

    /// <summary>
    /// 编辑项目解上锁记录
    /// </summary>
    /// <param name="entity">实体对象</param>
    public void Update(ProjectLockLog entity, IEnumerable<string>? attachments)
    {

        try
        {
            applicationContext.Transaction.Begin();//开始事务
            projectLockLogRepository.Update(entity);

            #region 附件

            var personAttachments = projectAttachmentService.GetProjectAttachmentsByObjectIdAndType(entity.Id, 附件类型.历史状态复核证明, 项目附件租户.ProjectLockLog).Select(a => a.Id);
            projectAttachmentService.Deleted(personAttachments);
            if (attachments != null && attachments.Any())
            {
                foreach (var item in attachments)
                {
                    ProjectAttachment projectAttachment = new()
                    {
                        Id = Guid.NewGuid().ToString().Replace("-", ""),
                        AttachmentId = item,
                        ObjectId = entity.Id.ToString(),
                        AttachmentType = 附件类型.历史状态复核证明,
                        CreateTime = DateTime.Now,
                        Tenant = 项目附件租户.ProjectLockLog
                    };
                    projectAttachmentService.Create(projectAttachment);
                }
            }
            #endregion 附件
            applicationContext.Transaction.Complete();//完成事务
        }
        catch (Exception ex)
        {
            applicationContext.Transaction.Abort();//回滚事务
            logger.LogError(ex, $"历史状态复核失败:{entity.Code}");
            throw new BusinessException("历史状态复核失败");
        }
    }


    /// <summary>
    /// 项目解上锁记录分页列表
    /// </summary>
    /// <param name="query">查询参数</param>
    /// <param name="pageIndex">当前页码</param>
    /// <param name="pageSize">每页显示条数</param>
    /// <returns></returns>
    public IPagedList<ProjectLockLog> GetProjectLockLogs(ProjectLockLogQuery query, int pageIndex, int pageSize)
    {
        return projectLockLogRepository.GetProjectLockLogs(query, pageIndex, pageSize);
    }

    public IPagedList<ProjectLockLog> GetProjectLockLogsByLock(ProjectLockLogQuery query, int pageIndex, int pageSize)
    {
        return projectLockLogRepository.GetProjectLockLogsByLock(query, pageIndex, pageSize);
    }
    public IEnumerable<ProjectLockLog> GetProjectLockLogsByProjectId(int projectId)
    {
        return projectLockLogRepository.GetProjectLockLogsByProjectId(projectId);
    }

    public ProjectLockLog? GetProjectLockLogByCode(string code)
    {
        return projectLockLogRepository.GetProjectLockLogByCode(code);
    }

    /// <summary>
    /// 历史状态复核验证
    /// </summary>
    /// <param name="data"></param>
    /// <exception cref="NotImplementedException"></exception>
    public void Verify(ProjectLockLog entity)
    {
        IEnumerable<ProjectLockLog> projectLockLogs = GetProjectLockLogsByProjectId(entity.ProjectId);
        if (projectLockLogs.Count() > 3)
            throw new BusinessException("当前项目的历史锁定记录超过三次，不能进行复核");
        ReportProjectMonth? reportProjectMonth = reportProjectMonthService.GetReportProjectMonthByProjectId(entity.ProjectId).FirstOrDefault(a => a.Month == entity.LockMonth);
        if (reportProjectMonth != null)
        {
            if (reportProjectMonth.IncomeStatus != 落实状态.已落实)
                throw new BusinessException("当前进账状态不正常，不能进行复核");
        }
        //\2、当前进账状态为绿色预警；3、农牧民施工队可以使用，不设3次上限
    }

    public void Update(ProjectLockLog entity)
    {
        projectLockLogRepository.Update(entity);
    }
}